/**
 * Copyright &copy; 2012-2016 <a href="https://github.com/thinkgem/jeesite">JeeSite</a> All rights reserved.
 */
package com.thinkgem.jeesite.modules.sys.web.customer;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.ConstraintViolationException;

import com.google.common.collect.Lists;
import com.thinkgem.jeesite.common.beanvalidator.BeanValidators;
import com.thinkgem.jeesite.common.utils.DateUtils;
import com.thinkgem.jeesite.common.utils.excel.ExportExcel;
import com.thinkgem.jeesite.common.utils.excel.ImportExcel;
import com.thinkgem.jeesite.modules.sys.entity.Office;
import com.thinkgem.jeesite.modules.sys.entity.User;
import com.thinkgem.jeesite.modules.sys.entity.member.Member;
import com.thinkgem.jeesite.modules.sys.service.DictService;
import com.thinkgem.jeesite.modules.sys.service.OfficeService;
import com.thinkgem.jeesite.modules.sys.service.SystemService;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.thinkgem.jeesite.common.config.Global;
import com.thinkgem.jeesite.common.persistence.Page;
import com.thinkgem.jeesite.common.web.BaseController;
import com.thinkgem.jeesite.common.utils.StringUtils;
import com.thinkgem.jeesite.modules.sys.entity.customer.Customer;
import com.thinkgem.jeesite.modules.sys.service.customer.CustomerService;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

/**
 * customerController
 * @author jin
 * @version 2018-04-23
 */
@Controller
@RequestMapping(value = "${adminPath}/sys/customer/customer")
public class CustomerController extends BaseController {

	@Autowired
	private CustomerService customerService;
	@Autowired
	private DictService dictService;
	@Autowired
	private OfficeService officeService;
	@Autowired
	private SystemService systemService;
	
	@ModelAttribute
	public Customer get(@RequestParam(required=false) String id) {
		Customer entity = null;
		if (StringUtils.isNotBlank(id)){
			entity = customerService.get(id);
		}
		if (entity == null){
			entity = new Customer();
		}
		return entity;
	}
	
	@RequiresPermissions("sys:customer:customer:view")
	@RequestMapping(value = {"list", ""})
	public String list(Customer customer, HttpServletRequest request, HttpServletResponse response, Model model) {
		Page<Customer> page = customerService.findPage(new Page<Customer>(request, response), customer); 
		model.addAttribute("page", page);
		return "modules/sys/customer/customerList";
	}

	@RequiresPermissions("sys:customer:customer:view")
	@RequestMapping(value = "form")
	public String form(Customer customer, Model model) {
		model.addAttribute("customer", customer);
		return "modules/sys/customer/customerForm";
	}

	@RequiresPermissions("sys:customer:customer:edit")
	@RequestMapping(value = "save")
	public String save(Customer customer, Model model, RedirectAttributes redirectAttributes) {
		if (!beanValidator(model, customer)){
			return form(customer, model);
		}
		if(customer.getDq()!=null || customer.getDq().length()>0){
             User user = new User();
			Office office =new Office();
			office.setId(customer.getDq());
             user.setOffice(office);
             customer.setDqName(systemService.getkfName(user));
		}
		if(customer.getDaoFlag()==null || customer.getDaoFlag().length()==0){
			customer.setDaoFlag("0");
		}
		customerService.save(customer);
		addMessage(redirectAttributes, "保存客户成功");
		return "redirect:"+Global.getAdminPath()+"/sys/customer/customer/?repage";
	}
	
	@RequiresPermissions("sys:customer:customer:del")
	@RequestMapping(value = "delete")
	public String delete(Customer customer, RedirectAttributes redirectAttributes) {
		customerService.delete(customer);
		addMessage(redirectAttributes, "删除导入客户成功");
		return "redirect:"+Global.getAdminPath()+"/sys/customer/customer/?repage";
	}

	/**
	 * 导出用户数据
	 * @param customer
	 * @param request
	 * @param response
	 * @param redirectAttributes
	 * @return
	 */
	@RequiresPermissions("sys:customer:customer:view")
	@RequestMapping(value = "export", method= RequestMethod.POST)
	public String exportFile(Customer customer, HttpServletRequest request, HttpServletResponse response, RedirectAttributes redirectAttributes) {
		try {
			String fileName = "报警用户数据"+ DateUtils.getDate("yyyyMMddHHmmss")+".xlsx";
			Page<Customer> page = customerService.findUser(new Page<Customer>(request, response, -1), customer);
			new ExportExcel("用户数据", Customer.class).setDataList(page.getList()).write(response, fileName).dispose();
			return null;
		} catch (Exception e) {
			addMessage(redirectAttributes, "导出用户失败！失败信息："+e.getMessage());
		}
		return "redirect:"+Global.getAdminPath()+"/sys/customer/customer/?repage";
	}

	/**
	 * 导入用户数据
	 * @param file
	 * @param redirectAttributes
	 * @return
	 */
	@RequiresPermissions("sys:customer:customer:view")
	@RequestMapping(value = "import", method=RequestMethod.POST)
	public String importFile(MultipartFile file, RedirectAttributes redirectAttributes) {
		if(Global.isDemoMode()){
			addMessage(redirectAttributes, "演示模式，不允许操作！");
			return "redirect:"+Global.getAdminPath()+"/sys/customer/customer/?repage";
		}
		try {
			int successNum = 0;
			int failureNum = 0;
			StringBuilder failureMsg = new StringBuilder();
			ImportExcel ei = new ImportExcel(file, 1, 0);
			List<Customer> list = ei.getDataList(Customer.class);
			for (Customer customer : list){
				try{
//					if ("true".equals(checkLoginName("", user.getLoginName()))){
//						member.setPassword(SystemService.entryptPassword("123456"));

					if("0".equals(customerService.checkLiId(customer.getLiId())) && customer.getLiId() != null && customer.getLiId().length()!= 0 ){
						if(customer.getSex()!= null && customer.getSex().length()!=0) {
							customer.setSex(dictService.setSex(customer.getSex()));
						}
						if(customer.getDqName()!= null && customer.getDqName().length()!=0){
							customer.setDq(systemService.getOfficeId(customer.getDqName()));
						}
						customer.setDaoFlag("0");
						if(customer.getBaoTime()!= null && customer.getBaoTime().length()!=0){
							SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
							customer.setBaTime(sdf.parse(customer.getBaoTime()));
						}
                        if(customer.getFashenTime()!= null && customer.getFashenTime().length()!=0){
							SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
							customer.setFsTime(sdf.parse(customer.getFashenTime()));
						}
						if(customer.getZhongdaTime()!= null && customer.getZhongdaTime().length()!=0){
							SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
							customer.setZdTime(sdf.parse(customer.getZhongdaTime()));
						}
						if(customer.getShenguTime()!= null && customer.getShenguTime().length()!=0){
							SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
							customer.setSgTime(sdf.parse(customer.getShenguTime()));
						}
						if(customer.getJiandingTime()!= null && customer.getJiandingTime().length()!=0){
							SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
							customer.setJdTime(sdf.parse(customer.getJiandingTime()));
						}
						if(customer.getShouliTime()!= null && customer.getShouliTime().length()!=0){
							SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
							customer.setSlTime(sdf.parse(customer.getShouliTime()));
						}
						BeanValidators.validateWithException(validator, customer);
						customerService.save(customer);
						successNum++;
					}else{
						failureMsg.append("<br/>该用户身份证 "+customer.getLiId()+" 已存在; ");
						failureNum++;
					}
				}catch(ConstraintViolationException ex){
					failureMsg.append("<br/>姓名 "+customer.getName()+" 导入失败：");
					List<String> messageList = BeanValidators.extractPropertyAndMessageAsList(ex, ": ");
					for (String message : messageList){
						failureMsg.append(message+"; ");
						failureNum++;
					}
				}catch (Exception ex) {
//
				}
			}
			if (failureNum>0){
				failureMsg.insert(0, "，失败 "+failureNum+" 条用户，导入信息如下：");
			}
			addMessage(redirectAttributes, "已成功导入 "+successNum+" 条用户"+failureMsg);
		} catch (Exception e) {
			addMessage(redirectAttributes, "导入用户失败！失败信息："+e.getMessage());
		}
		return "redirect:"+Global.getAdminPath()+"/sys/customer/customer/?repage";
	}

	/**
	 * 下载导入用户数据模板
	 * @param response
	 * @param redirectAttributes
	 * @return
	 */
	@RequiresPermissions("sys:customer:customer:view")
	@RequestMapping(value = "import/template")
	public String importFileTemplate(HttpServletResponse response, RedirectAttributes redirectAttributes) {
		try {
			String fileName = "预警客户数据导入模板.xlsx";
			List<Customer> list = Lists.newArrayList(); list.add(new Customer());
			new ExportExcel("理赔案件督查清单", Customer.class, 2).setDataList(list).write(response, fileName).dispose();
			return null;
		} catch (Exception e) {
			addMessage(redirectAttributes, "导入模板下载失败！失败信息："+e.getMessage());
		}
		return "redirect:"+Global.getAdminPath()+"/sys/customer/customer/?repage";
	}

	@RequestMapping(value = "sbzd")
	public String sbzd(String id,Model model){
		Customer customer = customerService.get(id);
		model.addAttribute("customer",customer);
		return "modules/sys/customer/sbzd";
	}
}